<template>
  <view class="create-paitent">
    <view class="navbar">
      <uni-nav-bar @clickLeft="goback" leftIcon="left" fixed="true" border="false" color="#FFF" statusBar="true"
        backgroundColor="#22b9a3" :title="title" />
    </view>
    <view class="content">
      <uni-forms :modelValue="formData">
        <uni-row>
          <uni-col :span="18" offset="1">
            <uni-forms-item label="姓名" name="name" required labelWidth="200rpx">
              <uni-easyinput type="text" v-model="formData.name" placeholder="请填写您的姓名" all />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="18" offset="1">
            <uni-forms-item label="性别" name="sex" required labelWidth="200rpx">
              <uni-data-checkbox v-model="formData.sex" :localdata="sexs" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="18" offset="1">
            <uni-forms-item label="身份证号码" name="cardNum" required labelWidth="200rpx">
              <uni-easyinput type="idcard" v-model="formData.cardNum" placeholder="请填写就诊人身份证号码" maxlength="18" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="18" offset=1>
            <uni-forms-item label="联系方式" name="phone" required labelWidth="200rpx">
              <uni-easyinput type="number" v-model="formData.phone" placeholder="请填写就诊人手机号" all maxlength="11" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="18" offset="1">
            <uni-forms-item label="就诊人关系" required name="relation" labelWidth="200rpx">
              <view>
                <picker @change="pickerRelationChange" :value="index" :range="relationList" mode="selector">
                  <view class="jobinput">{{relationList[index]}}</view>
                </picker>
              </view>
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="18" offset="1">
            <uni-forms-item label="行动是否方便" name="sex" required labelWidth="210rpx">
              <uni-data-checkbox v-model="formData.isWalk" :localdata="walk" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
      </uni-forms>
    </view>
    <view class="tip">
      <text>提示：未满18周岁请在监护人陪同下就诊</text>
    </view>
    <view class="card" @click="submitInfo">
      <view class="buy-btn">保存就诊人</view>
    </view>
  </view>
</template>

<script setup>
  import * as http from '@/utils/http'
  import {
    showToastAndDo
  } from '@/utils/toast.js'
  import {
    ref
  } from 'vue'
  import {
    useUserInfo
  } from '@/stores/userinfo.js';
  import {
    useSwitch
  } from '@/stores/switch.js'
  import {
    onLoad
  } from '@dcloudio/uni-app'

  const title = ref()
  onLoad(async (option) => {
    //判断登录信息
    if (Number.isFinite(+option.id)) {
      title.value = '修改就诊人'
      formData.value.id = option.id
      const result = await http.getRequest("/peizhen/paitent/get", {
        id: option.id
      })
      if (result.code == 0) {
        formData.value = result.data
      } else {
        uni.showToast({
          title: '获取陪诊人信息失败',
          icon: 'error',
          duration: 1000
        })
      }
    } else {
      title.value = '添加就诊人'
    }
  })
  const userInfo = useUserInfo()
  const formData = ref({})

  function goback() {
    uni.navigateBack()
  }
  const sexs = [{
    text: '男',
    value: 1
  }, {
    text: '女',
    value: 2
  }];
  const relationList = ['本人', '父亲', '母亲', '配偶', '祖父或外祖父', '祖母或外祖母', '其他关系']
  const index = ref(0)

  function pickerRelationChange(e) {
    formData.value.relation = relationList[e.detail.value]
    index.value = e.detail.value
  }

  const walk = [{
    text: '行动方便',
    value: 1
  }, {
    text: '行动不便',
    value: 2
  }]


  async function submitInfo() {
   
    if (validateForm()) {
      // 校验通过，执行提交操作   memberId:userInfo.loginData.userId
      formData.value.memberId = userInfo.loginData.userId
      if (formData.value.id) {
        const result = await http.postRequest('/peizhen/paitent/update', formData.value)
        if (result.code == 0) {
          showToastAndDo('修改成功', 'success', 1000, () => {
            uni.navigateBack()
          })
        }
      } else {
        const result = await http.postRequest('/peizhen/paitent/create', formData.value)
        if (result.code == 0) {
          showToastAndDo('添加成功', 'success', 1000, () => {
            uni.navigateBack()
          })
        } else if (result.code == 1001000011) {
          showToastAndDo(result.msg, 'error', 1000, () => {
          })
        }
      }
      //返回后需要重新加载数据
      useSwitch().controlReloadPaitent(true)
    }

  }

  function validateForm() {
    const {
      name,
      phone,
      cardNum,
      isWalk,
      relation,
      sex

    } = formData.value
    // 姓名校验（简单示例，实际可能更复杂）  
    if (!name || name.trim() === '') {
      uni.showToast({
        title: '姓名不能为空',
        icon: 'none'
      });
      return false;
    }
    // 手机号校验  
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      uni.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return false;
    }

    // 身份证号码校验  
    if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(cardNum)) {
      uni.showToast({
        title: '身份证号码格式不正确',
        icon: 'none'
      });
      return false;
    }
    return true;
  }
</script>

<style lang="scss">
  .navbar ::v-deep .uni-nav-bar-text {
    font-size: $uni-font-size-title !important;
    font-family: "siyuan";
  }

  .create-paitent {
    background-color: $uni-bg-color-grey;
    height: 100vh;
  }

  .content {
    padding-top: 40rpx;
    background-color: #fff;
  }

  .jobinput {
    font-size: 30rpx;
    height: 60rpx;
    line-height: 60rpx;
    border-bottom: solid 1px #f5f5f5;
    text-align: center;
  }

  .card {
    bottom: 10rpx;
    width: 100%;
    text-align: center;
    padding: 20rpx;
    border-radius: 10rpx;
  }


  .buy-btn {
    margin: 10rpx;
    padding: 10rpx 40rpx;
    width: 80%;
    height: 50rpx;
    line-height: 50rpx;
    background-color: #22b9a3;
    color: #fff;
    border-radius: 50rpx;
    text-align: center;
    font-size: 35rpx;
  }

  .tip {
    text-align: center;
    padding-top: 20rpx;
    font-size: 30rpx;
    color: #464646;
  }
</style>